package com.sunseagear.wind.modules.sys.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.sunseagear.common.utils.ObjectUtils;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunseagear.common.base.http.R;
import com.sunseagear.common.base.http.RPage;
import com.sunseagear.common.base.mvc.controller.BaseBeanController;
import com.sunseagear.common.utils.DateUtils;
import com.sunseagear.common.utils.StringUtils;
import com.sunseagear.wind.common.aspectj.annotation.Log;
import com.sunseagear.wind.common.aspectj.enums.LogType;
import com.sunseagear.wind.common.response.ResponseError;
import com.sunseagear.wind.common.utils.UserUtils;
import com.sunseagear.wind.common.utils.excel.ExportExcel;
import com.sunseagear.wind.modules.sys.dto.ChangePasswordDto;
import com.sunseagear.wind.modules.sys.entity.User;
import com.sunseagear.wind.modules.sys.entity.UserRole;
import com.sunseagear.wind.modules.sys.entity.query.SysUserQuery;
import com.sunseagear.wind.modules.sys.service.IRoleService;
import com.sunseagear.wind.modules.sys.service.IUserRoleService;
import com.sunseagear.wind.modules.sys.service.IUserService;
import com.sunseagear.wind.modules.sys.service.impl.OrganizationServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *
 * @version V1.0
 * @package com.sunseagear.wind.modules.sys.controller
 * @title: 消息模版控制器
 * @description: 消息模版控制器 * @date: 2018-09-03 15:10:10
 * @copyright: 2018 www.sunseagear.com Inc. All rights reserved.
 */

@RestController
@RequestMapping("/sys/user")
@Log(title = "用户管理")
@RequiredArgsConstructor
public class UserController extends BaseBeanController {
    private final IUserService userService;
    private final IUserRoleService userRoleService;
    private final IRoleService roleService;
    private final OrganizationServiceImpl organizationService;

    /**
     * 根据页码和每页记录数，以及查询条件动态加载数据
     */
    @GetMapping("list")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("sys:user:list")
    public RPage<User> list(SysUserQuery query) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("t.tenant_id", UserUtils.getTenantId());
        queryWrapper.like(ObjectUtils.isNotEmpty(query.getRealname()), "t.realname", query.getRealname());
        queryWrapper.like(ObjectUtils.isNotEmpty(query.getUsername()), "t.username", query.getUsername());
        queryWrapper.like(ObjectUtils.isNotEmpty(query.getPhone()), "t.phone", query.getPhone());
        queryWrapper.nested(ObjectUtils.isNotEmpty(query.getKeyWords()),i->
                i.like("t.phone", query.getKeyWords())
                        .or().like("t.realname", query.getKeyWords())
                        .or().like("t.username", query.getKeyWords()));
        queryWrapper.in(ObjectUtil.isNotEmpty(query.getOrganizationId()), "t.organization_id", organizationService.getChildrenIdsAndSelf(query.getOrganizationId()));
        // 预处理
        Page<User> pageBean = userService.page(getPage(), queryWrapper);
        return RPage.success(pageBean);
    }

    @PostMapping("add")
    @Log(logType = LogType.INSERT)
    @SaCheckPermission("sys:user:add")
    public R<Void> add(@Validated @RequestBody User entity) {
        //账号重复
        if (userService.count(new LambdaQueryWrapper<User>().eq(User::getUsername, entity.getUsername())) > 0) {
            return R.fail("账号重复");
        }
        entity.setTenantId(UserUtils.getTenantId());
        userService.save(entity);
        //保存之后
        afterSave(entity, entity.getRoleIdList());
        return R.success("添加成功");
    }

    /**
     * 修改
     * @param entity 实体对象
     * @return 操作结果
     */
    @PutMapping("update")
    @Log(logType = LogType.UPDATE)
    @SaCheckPermission("sys:user:update")
    public R<Void> update(@Validated @RequestBody User entity) {
        //账号重复
        if (userService.count(new QueryWrapper<User>().ne("id", entity.getId()).eq("username", entity.getUsername())) > 0) {
            return R.fail("账号重复");
        }
        userService.updateById(entity);
        //保存之后
        afterSave(entity, entity.getRoleIdList());
        return R.success("更新成功");
    }

    /**
     * 删除
     * @param idList 主键集合
     * @return 操作结果
     */
    @DeleteMapping("delete")
    @Log(logType = LogType.DELETE)
    @SaCheckPermission("sys:user:delete")
    public R<Void> delete(@RequestBody List<Long> idList) {
        userService.removeBatchByIds(idList);
        return R.success("删除成功");
    }

    /**
     * 修改密码
     * @param id 用户id
     * @param dto 新密码dto对象
     * @return 操作结果
     */
    @PostMapping(value = "{id}/changePassword")
    @Log(logType = LogType.OTHER, title = "修改成功")
    @SaCheckPermission("sys:user:change:password")
    public R<Void> changePassword(@PathVariable("id") Long id,@RequestBody ChangePasswordDto dto) {
        userService.changePassword(id, dto.getPassword());
        return R.success("密码修改成功");
    }

    /**
     * 详情
     * @param id 用户id
     * @return 用户实体
     */
    @GetMapping("detail/{id}")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("sys:user:list")
    public R<User> detail(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        return R.success(user);
    }

    public void afterSave(User entity,List<String> roleIdList) {
        // 删除角色关联
        if (roleIdList != null && !roleIdList.isEmpty()) {
            userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", entity.getId()));
            List<UserRole> userRoleList = new ArrayList<>();
            for (String roleId : roleIdList) {
                UserRole userRole = new UserRole();
                userRole.setUserId(entity.getId());
                userRole.setRoleId(Long.parseLong(roleId));
                userRoleList.add(userRole);
            }
            userRoleService.saveBatch(userRoleList);
        }

    }

    @GetMapping("export")
    @Log(logType = LogType.EXPORT)
    @SaCheckPermission("sys:user:export")
    public R<Map<String, Object>> export(HttpServletRequest request) {
        HashMap<String, Object> response = new HashMap<>();
        try {
            //加入条件
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            // 子查询
            String organizationid = request.getParameter("organizationid");
            if (!StringUtils.isEmpty(organizationid)) {
                queryWrapper.eq("uo.organization_id", organizationid);
            }
            Page<User> pageBean = userService.page(getPage(), queryWrapper);
            String title = "用户信息";

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            List<User> records = pageBean.getRecords();
            new ExportExcel(title , User.class).setDataList(records).write(bos);
            byte[] bytes = bos.toByteArray();
            String bytesRes = StringUtils.bytesToHexString2(bytes);
            title = title + "-" + DateUtils.getDateTime();
            response.put("bytes", bytesRes);
            response.put("title", title);
            return R.success("导出成功", response);
        } catch (Exception e) {
            log.error("导出失败", e);
            return R.fail(ResponseError.NORMAL_ERROR, "导出失败");
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping(value = "info")
    @SaCheckLogin
    public R<User> info() {
        User user = UserUtils.getUser();
        user.setRoles(roleService.findListByUserId(user.getId()));
        return R.success(user);
    }

    /**
     * 更新用户信息
     */
    @PostMapping("my/update")
    @Log(logType = LogType.UPDATE, title = "用户更新")
    @SaCheckLogin
    public R<Void> myUpdate(@RequestBody User user) {
        Long userId = UserUtils.getUser().getId();
        User oldUser = userService.getById(userId);
        // 验证错误
        BeanUtils.copyProperties(user, oldUser);
        userService.saveOrUpdate(oldUser);
        UserUtils.update(userId);
        return R.success("更新成功");
    }

    /**
     * 更新用户信息
     */
    @PostMapping("my/changePassword")
    @Log(logType = LogType.OTHER, title = "用户修改密码")
    @SaCheckLogin
    public R<Void> myChangePassword(@RequestBody ChangePasswordDto dto) {
        Long userId = UserUtils.getUser().getId();
        if (userService.checkPassword(userId, dto.getOldPassword())) {
            userService.changePassword(userId, dto.getPassword());
        } else {
            return R.fail("原密码错误");
        }
        return R.success("密码修改成功");
    }
}
